<template>
  <div class="basic-info-card">
    <div class="card-content">
      <!-- 设备信息卡片 -->
      <div class="info-card" :class="{ 'filled': formData.deviceInfo }" @click.stop.prevent="openEquipmentDialog" @mousedown.stop.prevent>
        <div class="fill-indicator"></div>
        <div class="card-label">
          设备信息
          <el-tooltip content="格式：设备名称-传感器编号-安装位置。如果是从监控页面跳转，设备信息会自动填入。" placement="top">
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="card-value" v-if="formData.deviceInfo">
          {{ formData.deviceInfo }}
        </div>
        <div class="card-placeholder" v-else>
          点击输入设备信息
        </div>

      </div>

      <!-- 故障等级卡片 -->
      <div class="info-card" :class="{ 'filled': formData.faultLevel !== undefined && formData.faultLevel !== '' }" @click.stop.prevent="openPriorityDialog" @mousedown.stop.prevent>
        <div class="fill-indicator"></div>
        <div class="card-label">
          故障等级
          <el-tooltip content="根据故障影响程度选择等级：紧急-影响生产安全；重要-影响生产效率；一般-不影响正常生产；轻微-轻微异常。" placement="top">
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="card-value" v-if="formData.faultLevel !== undefined && formData.faultLevel !== ''">
          {{ getPriorityText(formData.faultLevel) }}
        </div>
        <div class="card-placeholder" v-else>
          点击选择等级
        </div>

      </div>

      <!-- 报告人信息卡片 -->
      <div class="info-card" :class="{ 'filled': formData.reporter }" @click.stop.prevent="openReporterDialog" @mousedown.stop.prevent>
        <div class="fill-indicator"></div>
        <div class="card-label">
          报告人
          <el-tooltip content="从系统用户列表中选择报告人。" placement="top">
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="card-value" v-if="formData.reporter">
          {{ formData.reporter }}
        </div>
        <div class="card-placeholder" v-else>
          点击选择报告人
        </div>

      </div>

      <!-- 发生时间卡片 -->
      <div class="info-card" :class="{ 'filled': formData.occurredTime }" @click.stop.prevent="openTimeDialog" @mousedown.stop.prevent>
        <div class="fill-indicator"></div>
        <div class="card-label">
          发生时间
          <el-tooltip content="选择故障发生的具体时间。如果是从监控页面跳转，会自动填入当前时间。可手动调整为实际故障发生时间。" placement="top">
            <i class="el-icon-question help-icon"></i>
          </el-tooltip>
        </div>
        <div class="card-value" v-if="formData.occurredTime">
          {{ formatTime(formData.occurredTime) }}
        </div>
        <div class="card-placeholder" v-else>
          点击选择时间
        </div>

      </div>
    </div>

    <!-- 设备选择弹窗 -->
    <el-dialog
      title="输入设备信息"
      :visible.sync="equipmentDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="() => closeDialog('equipment')">
      <div>
        <el-input
          v-model="tempDeviceInfo"
          placeholder="请输入设备信息（格式：设备名称-传感器编号-安装位置）"
          class="clean-input">
        </el-input>
        <div style="margin-top: 10px; color: #909399; font-size: 12px;">
          示例：SP1主轴电机-SENSOR001-吸动端
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('equipment')">取消</el-button>
        <el-button type="primary" @click="saveEquipment">确定</el-button>
      </div>
    </el-dialog>

    <!-- 故障等级弹窗 -->
    <el-dialog
      title="故障等级"
      :visible.sync="priorityDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :before-close="() => closeDialog('priority')">
      <el-radio-group v-model="tempPriority">
        <el-radio :label="0" class="priority-radio high">紧急</el-radio>
        <el-radio :label="1" class="priority-radio medium">重要</el-radio>
        <el-radio :label="2" class="priority-radio low">一般</el-radio>
        <el-radio :label="3" class="priority-radio minimal">轻微</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('priority')">取消</el-button>
        <el-button type="primary" @click="savePriority">确定</el-button>
      </div>
    </el-dialog>

    <!-- 报告人弹窗 -->
    <el-dialog
      title="报告人"
      :visible.sync="reporterDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :before-close="() => closeDialog('reporter')">
      <el-select
        v-model="tempReporterId"
        filterable
        placeholder="请选择报告人"
        style="width: 100%">
        <el-option
          v-for="user in userList"
          :key="user.value"
          :label="user.label"
          :value="user.value">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('reporter')">取消</el-button>
        <el-button type="primary" @click="saveReporter">确定</el-button>
      </div>
    </el-dialog>

    <!-- 时间选择弹窗 -->
    <el-dialog
      title="发生时间"
      :visible.sync="timeDialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :before-close="() => closeDialog('time')">
      <el-date-picker
        v-model="tempTime"
        type="datetime"
        placeholder="选择发生时间"
        style="width: 100%"
        value-format="yyyy-MM-dd HH:mm:ss"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('time')">取消</el-button>
        <el-button type="primary" @click="saveTime">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dialogMixin from '@/mixins/dialogMixin'

export default {
  name: 'BasicInfoForm',
  mixins: [dialogMixin],
  props: {
    formData: {
      type: Object,
      required: true
    },
    userList: {
      type: Array,
      default: () => []
    },
    fields: {
      type: Array,
      default: () => []
    },
    rules: {
      type: Object,
      required: true
    },
    compact: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      equipmentDialogVisible: false,
      priorityDialogVisible: false,
      reporterDialogVisible: false,
      timeDialogVisible: false,
      tempDeviceInfo: '',
      tempPriority: null,
      tempReporter: '',
      tempReporterId: null,
      tempTime: ''
    }
  },
  watch: {
    'formData.faultLevel': {
      immediate: true,
      handler(val) {
        // 只有当值不为空时才设置 tempPriority
        this.tempPriority = (val !== undefined && val !== null && val !== '') ? Number(val) : null;
      }
    }
  },
  methods: {
    validate() {
      // 简单验证必填字段
      if (!this.formData.deviceInfo) {
        this.$message.error('请输入设备信息');
        return Promise.reject();
      }
      if (this.formData.faultLevel === undefined || this.formData.faultLevel === null || this.formData.faultLevel === '') {
        this.$message.error('请选择故障等级');
        return Promise.reject();
      }
      return Promise.resolve();
    },

    openEquipmentDialog() {
      this.safeOpenDialog(() => {
        this.tempDeviceInfo = this.formData.deviceInfo || '';
        this.equipmentDialogVisible = true;
      });
    },

    openPriorityDialog() {
      this.safeOpenDialog(() => {
        // 只有当值不为空时才设置 tempPriority，否则设为 null（无选中）
        this.tempPriority = (this.formData.faultLevel !== undefined &&
                            this.formData.faultLevel !== null &&
                            this.formData.faultLevel !== '') ? Number(this.formData.faultLevel) : null;
        this.priorityDialogVisible = true;
      });
    },

    openReporterDialog() {
      this.safeOpenDialog(() => {
        this.tempReporterId = this.formData.reporterId || null;
        this.reporterDialogVisible = true;
      });
    },

    openTimeDialog() {
      this.safeOpenDialog(() => {
        this.tempTime = this.formData.occurredTime || '';
        this.timeDialogVisible = true;
      });
    },

    saveEquipment() {
      this.formData.deviceInfo = this.tempDeviceInfo;
      // 解析设备信息并填充其他字段
      const parts = this.tempDeviceInfo.split('-');
      if (parts.length >= 1) this.formData.equipmentName = parts[0];
      if (parts.length >= 2) this.formData.sensorId = parts[1];
      if (parts.length >= 3) this.formData.sensorPosition = parts[2];
      this.closeDialog('equipment');
    },

    savePriority() {
      // 只有当用户选择了选项时才保存
      if (this.tempPriority !== null && this.tempPriority !== undefined) {
        this.formData.faultLevel = Number(this.tempPriority);
      }
      this.closeDialog('priority');
    },

    saveReporter() {
      const selectedUser = this.userList.find(user => user.value === this.tempReporterId);
      if (selectedUser) {
        this.formData.reporter = selectedUser.label;
        this.formData.reporterId = selectedUser.value;
      }
      this.closeDialog('reporter');
    },

    saveTime() {
      this.formData.occurredTime = this.tempTime;
      this.closeDialog('time');
    },

    closeDialog(type) {
      this.safeCloseDialog(() => {
        switch(type) {
          case 'equipment':
            this.equipmentDialogVisible = false;
            break;
          case 'priority':
            this.priorityDialogVisible = false;
            break;
          case 'reporter':
            this.reporterDialogVisible = false;
            break;
          case 'time':
            this.timeDialogVisible = false;
            break;
        }
      });
    },

    getPriorityText(level) {
      const map = {
        0: '紧急',
        1: '重要',
        2: '一般',
        3: '轻微'
      };
      return map[level] || level;
    },

    formatTime(time) {
      if (!time) return '';
      return new Date(time).toLocaleString('zh-CN');
    }
  }
}
</script>

<style scoped>
/* 基本信息卡片容器 */
.basic-info-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
}



/* 卡片内容 */
.card-content {
  padding: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  flex: 1;
}

/* 信息卡片 */
.info-card {
  background: #f8fafc;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 12px 12px 12px 20px;
  cursor: pointer;
  position: relative;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

/* 填写状态指示器 */
.fill-indicator {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: #e2e8f0;
  border-radius: 12px 0 0 12px;
  transition: all 0.3s ease;
}

.info-card.filled .fill-indicator {
  background: linear-gradient(135deg, #10b981, #059669);
  box-shadow: 0 0 8px rgba(16, 185, 129, 0.3);
}



.card-label {
  font-size: 12px;
  font-weight: 600;
  color: #64748b;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.help-icon {
  font-size: 14px;
  color: #9ca3af;
  cursor: help;
  transition: color 0.2s ease;
}

.help-icon:hover {
  color: #6b7280;
}

.card-value {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
  line-height: 1.5;
  flex: 1;
}

.card-placeholder {
  font-size: 14px;
  color: #94a3b8;
  font-style: italic;
  flex: 1;
}



/* 弹窗样式 */
.el-dialog__wrapper {
  z-index: 3000 !important;
}

.el-overlay {
  z-index: 2999 !important;
}

/* 日期选择器z-index修复 */
.el-picker-panel {
  z-index: 3001 !important;
}

.el-date-picker__time-header {
  z-index: 3001 !important;
}

.el-time-panel {
  z-index: 3002 !important;
}

/* 下拉选择器z-index修复 */
.el-select-dropdown {
  z-index: 3001 !important;
}

.el-popper {
  z-index: 3001 !important;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  border-radius: 8px;
  font-weight: 500;
  padding: 8px 16px;
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #10b981, #059669);
  border: none;
  box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3);
}



/* 优先级单选按钮样式 */
.priority-radio {
  display: block;
  margin-bottom: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.priority-radio.high {
  background: #fef2f2;
  border: 1px solid #fecaca;
}

.priority-radio.medium {
  background: #fffbeb;
  border: 1px solid #fed7aa;
}

.priority-radio.low {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
}

.priority-radio.minimal {
  background: #f9fafb;
  border: 1px solid #d1d5db;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .card-content {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}
</style>